
//获取应用实例
const app = getApp()
var commonData = require('../../data/data.js');
var commonController = require('../../data/commonControll.js');
var _dealImgUrl = "https://wxapi.zixunmanyou.com/GamePtImages/back/baozha.gif";
var _monsterApImgUrl = "https://wxapi.zixunmanyou.com/GamePtImages/back/monsterAp.gif";
var _currentHardType = 1;//当前难度级别
var _initNum = 0;
var _addTime = 0;
var _addNum = 0;
var _intervalTime = 0;
var _makePowerCd = 0;
var _makePowerNum = 0;






var _initPower = 0;
var _hpValue = 0;//动态
var _hpValue_static = 0;//静态用户血量
var _monsterTimeMinusCd = 0;
var isStop = false;//怪是否暂停
var _gloadbIntervalIdArr = [];//全局定时器ID数组,麻痹的小程序漏洞，关闭页面，不清除定时器和变量
var _lock_monsterDead = true;//由于删除数组中的怪，是settimeout,可能会出现并发情况
var _lock_uploadResutObj = false;//由于上传会有网络延迟，被怪打死，怪还会继续进行行走撞击，这里加锁防止重复提交
Page({
  data: {
    powerList: [],
    animationData_1: {},
    animationData: {},
    powerPlaceList: [],
    monsterList: [],
    cancelIsShow: false,
    currentPower: null,//当前选择的火力,
    hpCell: 100,
    monsterTimeCell: 100,//出怪时间轴段数，根据设置，每隔几秒，减1
    fightSeconds: 100,//防守总秒数
    width: 0,
    height: 0,
    soureValue: 0,
    stopMonsterSkill: {},
    isShowStopAnimation: false,
    allHartSkill: {},
    isShowAllHartAnimation: false,
    priceValue: 0,
    isShowErrorMsg: false,
    errorMsg: "",
    isStopMonsters:0,
    currentSecond: 0,//开始战斗时，计时器,
    catPower: 50//召唤猫的能量
  },
  //计算结果
  sendFightResult: function () {
    if (_lock_uploadResutObj)
      return;
    
    wx.showLoading({
      title: '战绩上传中',
    })
    _lock_uploadResutObj = true;
    var that = this;
    var hardType = _currentHardType;
    this.closeData();
    wx.request({
      url: app.appSetting.host + "Weixin/UpLoadFightResult",
      data: {
        UserId: app.globalData.userInfo.UserId,
        PriceValue: this.data.priceValue,
        PowerValue: this.data.catPower,
        SoureValue: this.data.soureValue,
        HardType: hardType
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
       
        wx.hideLoading();
        if (res.data.Status == 0) {
          app.showMsg("上传完成");
          wx.reLaunch({
            url: 'fightResult?power=' + that.data.catPower + '&price=' + that.data.priceValue + '&soure=' + that.data.soureValue + '&hardtype=' + hardType,
          })
        } else {
          app.showMsg(res.data.Message);
          wx.showModal({
            title: '提醒',
            content: '上传战绩异常,是否进行重试?取消则返回首页',
            success: function (res) {
              if (res.confirm) {
                _lock_uploadResutObj = false;
              } else if (res.cancel) {
                wx.switchTab({
                  url: '/pages/index/index',
                })
              }
            }
          })
        }

      }
    })
  },
  //展示提示信息
  showErrorTip: function (msg) {
    if (this.data.isShowErrorMsg)
      return false;
    this.setData({
      isShowErrorMsg: true,
      errorMsg: msg
    })
    var that = this;
    setTimeout(function () {
      that.setData({
        isShowErrorMsg: false,
        errorMsg: ""
      })
    }, 1000)
  },
  //暂停怪大招
  useStopSkill: function () {
    var that = this;
    //先判断冷却时间是否结束
    if (this.data.stopMonsterSkill.cdTime > 0)
      return false;
    
    //重新恢复冷却，并且播放特效动画
    var _stopMonsterSkill = this.data.stopMonsterSkill;
    var stopTime = commonData.stopMonsterSkill.time;
    _stopMonsterSkill.cdTime = commonData.stopMonsterSkill.cdTime;
    _stopMonsterSkill.isShow = true;

    this.setData({
      stopMonsterSkill: _stopMonsterSkill,
      isShowStopAnimation: true,
      isStopMonsters: 1
    });
    setTimeout(function () {
      that.setData({
        isShowStopAnimation: false,
        isStopMonsters:0
      })
    }, stopTime*1000)

  },
  //全屏伤害大招
  useAllHart: function () {
    var that = this;
    if (this.data.allHartSkill.cdTime > 0)
      return false;
    //刷新冷却时间,并且播放特效动画
    var _allHartSkill = this.data.allHartSkill;
    _allHartSkill.cdTime = commonData.allHartSkill.cdTime;
    _allHartSkill.isShow = true;
    this.setData({
      allHartSkill: _allHartSkill,
      isShowAllHartAnimation: true
    });
    //1秒后，检测全屏伤害
    setTimeout(that.allCollide, 1000);
    //2秒后，取消动画
    setTimeout(function () {
      that.setData({
        isShowAllHartAnimation: false
      })
    }, 2000)
  },
  //全屏伤害检测
  allCollide: function () {
    var _monsterList = this.data.monsterList;
    if (_monsterList.length > 0) {
      for (var i = _monsterList.length - 1; i >= 0; i--) {
        //显示伤害
        this.showMonsterHart(_monsterList[i].guid, this.data.allHartSkill.ap)
        //判断血量
        if ((_monsterList[i].hp - this.data.allHartSkill.ap) > 0) {
          //怪没死，更新怪血量
          this.updateMonsterHp(_monsterList[i].guid, _monsterList[i].hp - this.data.allHartSkill.ap);
        } else {
          //怪死=》加分数，加金币
          this.AnimationMonsterDealy(_monsterList[i].guid, 2);
          //清除当前怪行走定时器
          clearInterval(_monsterList[i].intervalId);
         
          this.setData({
            soureValue: this.data.soureValue + _monsterList[i].soure,
            priceValue: this.data.priceValue + _monsterList[i].price,
            catPower: this.data.catPower + _monsterList[i].power
          });
        }
      }

    }
  },

  setPow: function (e) {
    //判断是否选择
    if (this.data.currentPower == null) {
      return false;
    }
    //判断当前位置是否被用
    var thisPlace = commonController.common.placeInstance.getPlaceInstance(e.currentTarget.dataset.setid, this.data.powerPlaceList);
    if (thisPlace.isuse) {
      return false;
    }
    var _tempPlaceList = this.data.powerPlaceList;
    _tempPlaceList[thisPlace.id - 1].isuse = true;
    _tempPlaceList[thisPlace.id - 1].imgUrl = this.data.currentPower.imgUrl;
    _tempPlaceList[thisPlace.id - 1].className = "powerImg";
    //给当前位置赋值
    this.setData({
      powerPlaceList: _tempPlaceList
    });
    var _currentPower = this.data.currentPower;
    //取消放置圈提示
    this.mangerPlaceTip(-1);
    //取消火力选择提示
    this.mangerPowerTip(-1, this.data.currentPower);
    //创建攻击
    this.CreateAttackAnimation(thisPlace, _currentPower, e.detail.y);
  },
  //放置圈提示和取消
  mangerPlaceTip: function (optionType) {//1设置，-1取消
    var _tempPlaceList = this.data.powerPlaceList;
    var _count = 0;
    //放置圈提示
    for (var i = 0; i < _tempPlaceList.length; i++) {
      if (!_tempPlaceList[i].isuse) {
        _tempPlaceList[i].className = optionType == 1 ? "setTip" : "powerImg";
        _count++;
      }
    }
    if (_count > 0) {
      this.setData({
        powerPlaceList: _tempPlaceList,
        cancelIsShow: optionType == 1 ? true : false
      });

    } else {
      app.showMsg("已没有位置放置");
    }
  },
  //火力选择提示控制
  mangerPowerTip: function (optionType, currentChose) {//1显示，-1取消
    var _powerList = this.data.powerList;
    for (var i = 0; i < _powerList.length; i++) {
      if (_powerList[i].id == currentChose.id) {
        _powerList[i].className = optionType == 1 ? "choseTip" : "skillImg";
        break;
      }
    }
    this.setData({
      powerList: _powerList,
      currentPower: optionType == 1 ? currentChose : null
    });
  },
  //选择
  chosePow: function (e) {
    //还原之前的选择
    if (this.data.currentPower != null) {
      var _tempPowerList = this.data.powerList;
      for (var i = 0; i < _tempPowerList.length; i++) {
        if (_tempPowerList[i].id == this.data.currentPower.id) {
          _tempPowerList[i].className = "skillImg";
          break;
        }
      }
      this.setData({
        powerList: _tempPowerList,
        currentPower: null
      })
    }
    //判断哪些格子没使用
    var currentChose = this.getItemById(e.currentTarget.dataset.powid, 1);
    //进行各种资源验证
    if (currentChose.needPower > this.data.catPower) {
      this.showErrorTip("能量不足");
      return false;
    }
    //选择提示
    this.mangerPowerTip(1, currentChose);
    //放置圈提示
    this.mangerPlaceTip(1);

  },
  //根据ID获取实例，itemType：1火力，2位置
  getItemById: function (id, itemType) {
    var _list = [];
    switch (itemType) {
      case 1:
        _list = commonData.powers;
        
        break;
      case 2:
        _list = commonData.powerPlaceList;
        break;
    }
    var res = null;
    for (var i = 0; i < _list.length; i++) {
      if (_list[i].id == id) {
        res = _list[i];
        break;
      }
    }
    return res;
  },
  //取消选择
  cancelChose: function () {
    //取消放置圈提示
    this.mangerPlaceTip(-1);
    //取消火力选择提示
    this.mangerPowerTip(-1, this.data.currentPower);
  },
  //获取屏幕高度，宽度
  getSystermMsg: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          width: res.windowWidth,
          height: res.windowHeight
        });
      }
    })
  },
  //开战，计时器
  FightTimer: function () {
    var that = this;
    var interval = setInterval(function () {
      that.setData({
        currentSecond: that.data.currentSecond + 1
      });
    }, 1000)
    _gloadbIntervalIdArr.push(interval);
  },
  //根据难度，初始化刷怪难度
  InitFreshMonsterConfig: function (hardLevel) {
   
    var config = {};
    switch (hardLevel) {
      case 1:
        config = commonData.refreshConfig.easyConfig;
        break;
      case 2:
        config = commonData.refreshConfig.hardConfig;
        break;
      case 3:
        config = commonData.refreshConfig.hellConfig;
        break;
    }
    
    _initNum = config.initNum;//初始数量
    _addTime = config.addTime;
    _addNum = config.addNum;
    _intervalTime = config.intervalTime;
    _makePowerCd = config.makePowerCd;
    _makePowerNum = config.makePowerNum;
    _initPower = config.initPower;
    _hpValue = config.hpValue;
    _hpValue_static = config.hpValue;
    _monsterTimeMinusCd = config.monsterTimeMinusCd;
    this.setData({
      catPower: _initPower,
      fightSeconds: _monsterTimeMinusCd *100
    })
    var that = this;
    var inter = setInterval(function () {
      that.setData({
        catPower: that.data.catPower + _makePowerNum
      })
    }, _makePowerCd * 1000)
    _gloadbIntervalIdArr.push(inter);
  },
  //随机创建怪物和动画.每次刷新初始2只，每过1分钟加一只，
  mangerMonsters: function () {
    this.FightTimer();
    if (_initNum == 0 || _addTime == 0 || _addNum == 0) {
      app.showMsg("初始化失败");
      return false;
    }
    var that = this;
    //parseInt(Math.random() * 100)
    var outInterval = setInterval(function () {
      //取出当次刷新怪物的数量
      var refreshMonsterCount = _initNum + parseInt(that.data.currentSecond / _addTime) * _addNum;
      //获得当次刷新的怪物实例集合
      var monstersArr = commonController.common.monsterInstance.getRandomMonsterArr(refreshMonsterCount, commonData, _currentHardType);

      //解决多只怪，在同一队列中，重叠的问题。
      var arr = commonController.common.monsterInstance.resolveOverlay(monstersArr);
      //处理给新刷新的怪
      that.createMonsterAnimation(arr);
    }, _intervalTime * 1000)
    _gloadbIntervalIdArr.push(outInterval);
  },
  //批量处理刷新怪动画
  createMonsterAnimation: function (arr) {
    var _tempList = this.data.monsterList;
    for (var i = 0; i < arr.length; i++) {
      _tempList.push(arr[i]);
    }

    //1.把刷新的怪实例，放进全局怪数组
    this.setData({
      monsterList: _tempList
    });
    //2.给这批刷新的怪实例添加行走动画
    for (var i = 0; i < arr.length; i++) {
      this.createIntervalForMonster(arr[i].guid);
    }
  },

  //给怪创建动画,由于一共就几种怪，怪多了一定会出现重复，所有单独有唯一标识，这里怪物行走，每次根据唯一标识从全局变量数组中获取实例，如果获取不到说明已经挂了，清楚当前定时器
  createIntervalForMonster: function (guid) {
    var monster = commonController.common.monsterInstance.getInstanceFromMonsterList(guid, this.data.monsterList);
    var maxTop = this.data.height - 310 - 50;//临界值。
    var _top = monster.top;
    var that = this;
    var interval = setInterval(function () {
      
      //给当前怪添加行走定时器序号
      if (monster.intervalId == undefined || monster.intervalId == 0 || monster.intervalId == "")
        that.BindIntervalIdForMonster(guid, interval)

      //判断是否使用了暂停怪技能
      
      if (that.data.isStopMonsters==0) {

        //如果怪没死，播放爆炸动画，消失，给玩家造成伤害
        if (monster.hp > 0 && _top >= maxTop) {
          clearInterval(interval);
          that.AnimationMonsterDealy(guid, 1);
          //给玩家造成伤害逻辑、
          that.monsterAttack(monster);
          return;
        }
        //验证逻辑，
        if (monster == null) {
          clearInterval(interval);
          return;
        }

        if (_top >= maxTop) {
          //超过界限，说明怪没死，自爆，造成伤害，并且从全局数组消除。回头写

          clearInterval(interval);
        } else {
          _top += monster.speed;
          that.updateMonsterMove(guid, _top);

        }
      }
    }, monster.moveCdTime);
    _gloadbIntervalIdArr.push(interval);
   
  },
  //给玩家造成伤害+后续逻辑
  monsterAttack: function (monster) {
    var surplusHp = _hpValue - monster.ap;
  
    if (surplusHp > 0) {
      //没死，更新血条百分比
      this.setData({
        hpCell: parseInt(surplusHp / _hpValue_static * 100)
      })
      _hpValue = surplusHp;
    } else {
      //玩家死了,退出战斗界面，进入统计
      this.setData({
        hpCell: 0
      })
      this.sendFightResult();

    }
  },
  //当前怪爆炸
  AnimationMonsterDealy: function (guid, t) {//1自爆攻击，2被打死
    var that = this;
    var _tempList = this.data.monsterList
    for (var i = 0; i < _tempList.length; i++) {
      if (guid == _tempList[i].guid) {
        _tempList[i].imgUrl = t == 1 ? _monsterApImgUrl : _dealImgUrl;
        _tempList[i].isDead = true;//死亡
        break;
      }
    }
    this.setData({
      monsterList: _tempList
    });
  },
  //给当前怪绑定行走定时器
  BindIntervalIdForMonster: function (guid, intervalId) {
    var that = this;
    var _tempList = this.data.monsterList
    for (var i = 0; i < _tempList.length; i++) {
      if (guid == _tempList[i].guid) {
        _tempList[i].intervalId = intervalId;
        break;
      }
    }
    this.setData({
      monsterList: _tempList
    });
  },
  //用于清理死亡怪对象的任务
  DoDeadMonsterTask: function () {
    //统一处理死亡怪
    var that = this;

    var inter = setInterval(function () {
      var _list = [];
      for (var i = 0; i < that.data.monsterList.length; i++) {
        if (!that.data.monsterList[i].isDead) {
          _list.push(that.data.monsterList[i]);
        }
      }
      that.setData({
        monsterList: _list
      });
    }, 1000)
    _gloadbIntervalIdArr.push(inter);
  },
  //更新怪行走视图
  updateMonsterMove: function (guid, top) {
    var _tempList = this.data.monsterList
    for (var i = 0; i < _tempList.length; i++) {
      if (guid == _tempList[i].guid) {
        _tempList[i].top = top;
        break;
      }
    }
    this.setData({
      monsterList: _tempList
    });
  },

  //初始化大招冷却时间
  initSpecialSkillCd: function (skillType) {//1时间暂停，2全屏伤害
    var that = this;
    switch (skillType) {
      case 1:
        var inter = setInterval(function () {
          var _tempStopMonsterSkill = that.data.stopMonsterSkill;
          if (_tempStopMonsterSkill.isShow) {//如果还是显示说明还在Cd
            _tempStopMonsterSkill.cdTime -= 1;
            if (_tempStopMonsterSkill.cdTime <= 0)
              _tempStopMonsterSkill.isShow = false;
            that.setData({
              stopMonsterSkill: _tempStopMonsterSkill
            })
          }
        }, 1000)
        _gloadbIntervalIdArr.push(inter);
        break;
      case 2:
        var inter = setInterval(function () {
          var _tempAllHartSkill = that.data.allHartSkill;
          if (_tempAllHartSkill.isShow) {//如果还是显示说明还在Cd
            _tempAllHartSkill.cdTime -= 1;
            if (_tempAllHartSkill.cdTime <= 0)
              _tempAllHartSkill.isShow = false;
            that.setData({
              allHartSkill: _tempAllHartSkill
            })
          }
        }, 1000)
        _gloadbIntervalIdArr.push(inter);
        break;
    }
  },
  exsitFight: function () {
    var that = this;
    wx.showModal({
      title: '提醒',
      content: '现在退出将计算结果,确定要退出吗?',
      success: function (res) {
        if (res.confirm) {
          that.sendFightResult();
        } else if (res.cancel) {

        }
      }
    })
  },
  onLoad: function (option) {

    //根据难度初始化刷怪规则
    this.getSystermMsg();

    _currentHardType = parseInt(option.hardtype);
   
    //初始化刷新规则
    this.InitFreshMonsterConfig(_currentHardType);
    //初始化特殊技能大招的冷却时间事件
    this.initSpecialSkillCd(1);
    this.initSpecialSkillCd(2);
    this.setData({
      //animationData: animation.export(),
      powerList: commonData.currentFightPowers,
      powerPlaceList: commonData.powerPlaceList,
      stopMonsterSkill: commonData.stopMonsterSkill,
      allHartSkill: commonData.allHartSkill,
    });
    //怪物控制器
    setTimeout(this.mangerMonsters, 5000);
    //怪物死亡任务
    this.DoDeadMonsterTask();
    this.monsterTimeControll();
    this.fightSeconds();
  },
  //关闭当前页面时进来
  onUnload: function () {
    this.closeData();
  },
  //恢复页面数据，清除定时器
  closeData: function () {
    
    //清除所有定时器
    for (var i = 0; i < _gloadbIntervalIdArr.length; i++) {
      clearInterval(_gloadbIntervalIdArr[i]);
    }

    _currentHardType = 1;//当前难度级别
    _initNum = 0;
    _addTime = 0;
    _addNum = 0;
    _intervalTime = 0;
    _makePowerCd = 0;
    _makePowerNum = 0;
    _initPower = 0;
    _hpValue = 0;//动态
    _hpValue_static = 0;//静态用户血量
    _monsterTimeMinusCd = 0;

    
    _gloadbIntervalIdArr = [];
    _lock_uploadResutObj = false;//由于上传会有网络延迟，被怪打死，怪还会继续进行行走撞击，这里加锁防止重复提交
  },
  //出怪总段数控制器
  monsterTimeControll: function () {
    var that = this;
    var inter = setInterval(function () {
      //每5秒，时间少1%
      that.setData({
        monsterTimeCell: that.data.monsterTimeCell - 1
      })
      if (that.data.monsterTimeCell <= 0) {
        //战斗结束，统计结果
        that.sendFightResult();
      }
    }, _monsterTimeMinusCd * 1000)
    _gloadbIntervalIdArr.push(inter);
  },
  //出怪总秒数控制器
  fightSeconds: function () {
    var that = this;
    var inter = setInterval(function () {
      that.setData({
        fightSeconds: that.data.fightSeconds - 1
      })
    }, 1000)
    _gloadbIntervalIdArr.push(inter);
  },
  //创建攻击动画。
  CreateAttackAnimation: function (place, _currentPower, y) {//y就是当前位置距顶端界限的距离
    var that = this;
    var _top = 0;
    place.powerImgUrl = _currentPower.skillImgUrl;
    this.UpdatePlaceList(place);
    //扣除能量
    this.setData({
      catPower: this.data.catPower - _currentPower.needPower
    });
    var interval = setInterval(function () {
      //监测碰撞,判定攻击，现在所有位置的火力都是一种类型，有设定的打几只怪
      that.checkCollide(place.trackNum, _currentPower)
    }, place.cdTime * 1000);
    _gloadbIntervalIdArr.push(interval);
  },
  //检测火运动与怪碰撞+逻辑
  checkCollide: function (trackNum, _currentPower) {
    //原：获取和当前火力同序列的怪，怪从最顶端出发，怪当前的top就是Y坐标，计算当前火力的Y坐标，误差在一定像素内的算是碰撞，如果有多个怪满足，取最近的一个。
    //新：小程序技术问题，每一帧检测，实现不了。现在改为，火力没循环一次，根据打几只怪的设定对一条直线上怪进行攻击，
    //获取与当前火力同序列的怪集合
    var _monsterList = commonController.common.monsterInstance.getMonstersByTrackNum(trackNum, this.data.monsterList);
    if (_monsterList.length > 0) {
      var _count = 1;
      for (var i = _monsterList.length - 1; i >= 0; i--) {
        //判定火力攻击是否超过限制的怪数量
        if (_count <= _currentPower.apCount) {
          //显示伤害
          this.showMonsterHart(_monsterList[i].guid, _currentPower.ap)
          //判断血量
          if ((_monsterList[i].hp - _currentPower.ap) > 0) {
            //怪没死，更新怪血量
            this.updateMonsterHp(_monsterList[i].guid, _monsterList[i].hp - _currentPower.ap);
          } else {
            //怪死=》加分数，加金币,加猫晶
            //清除当前怪行走定时器
            clearInterval(_monsterList[i].intervalId);
           
            this.AnimationMonsterDealy(_monsterList[i].guid, 2);
           
            this.setData({
              soureValue: this.data.soureValue + _monsterList[i].soure,
              priceValue: this.data.priceValue + _monsterList[i].price,
              catPower: this.data.catPower + _monsterList[i].power
            });
          }
          _count++;
        }
      }

    }
  },
  //显示怪物伤害
  showMonsterHart: function (guid, ap) {
    var _list = this.data.monsterList;
    for (var i = 0; i < _list.length; i++) {
      if (_list[i].guid == guid) {
        _list[i].hart = ap;
        _list[i].isShowHart = true;
        break;
      }
    }
    this.setData({
      monsterList: _list
    });
    this.hideMonsterHart(guid);
  },
  //怪隐藏伤害
  hideMonsterHart: function (guid) {
    var that = this;
    //500毫秒后，隐藏
    setTimeout(function () {
      var _list = that.data.monsterList;
      for (var i = 0; i < _list.length; i++) {
        if (_list[i].guid == guid) {
          _list[i].isShowHart = false;
          break;
        }
      }
      that.setData({
        monsterList: _list
      });
    }, 500)
  },
  //更新怪血量
  updateMonsterHp: function (guid, hp) {
    var _list = this.data.monsterList;
    for (var i = 0; i < _list.length; i++) {
      if (_list[i].guid == guid) {
        _list[i].hp = hp;
        break;
      }
    }
    this.setData({
      monsterList: _list
    });
  },
  //更新视图位置数组
  UpdatePlaceList: function (place) {
    var _tempList = this.data.powerPlaceList;
    _tempList[place.id - 1].powerImgUrl = place.powerImgUrl;
    _tempList[place.id - 1].top = place.top;
    this.setData({
      powerPlaceList: _tempList
    });
  },

})
